package com.droid.mvvmlib.base;

import android.app.Application;

import com.droid.mvvmlib.databinding.BaseBindingQuickAdapter;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.lifecycle.MutableLiveData;

/**
 * 无分页ViewModel基类
 *
 * @author zyc0617
 * @since 2019/8/18 15:35
 */
public class BaseNonPagingViewModel<M extends BaseModel, D> extends UiChangeViewModel<M, D> implements BaseNonPagingModel.IModelListener<ArrayList<D>> {

    public final MutableLiveData<ObservableArrayList<D>> dataList = new MutableLiveData<>();
    public MutableLiveData<BaseBindingQuickAdapter> adapter = new MutableLiveData<>();

    public BaseNonPagingViewModel(@NonNull Application application) {
        this(application, null);
    }
    
    public BaseNonPagingViewModel(@NonNull Application application, M model) {
        super(application, model);
        dataList.setValue(new ObservableArrayList<>());
        if (model != null) {
            model.register(this);
        }
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (model != null) {
            model.unRegister(this);
        }
    }


    public void refresh() {
        model.getCachedDataAndLoad();
    }

    @Override
    public void tryToRefresh() {
        super.tryToRefresh();
    }

    @Override
    public void onLoadFinish(BaseNonPagingModel model, ArrayList<D> data, boolean isEmpty) {
        if (model == this.model) {
            dataList.getValue().clear();
            dataList.getValue().addAll(data);
            // 通知更新
            if (isEmpty) {
                viewStatus.setValue(ViewStatus.EMPTY);
                return;
            }
            viewStatus.setValue(ViewStatus.SHOW_CONTENT);
        }
    }

    @Override
    public void onLoadFail(BaseNonPagingModel model, String error) {
        errorMessage.setValue(error);
        viewStatus.setValue(ViewStatus.REFRESH_ERROR);
    }
}
